package com.zhugang.week08;

import java.util.ArrayList;
import java.util.List;

/**
 * @program algorithms
 * @description: combinationSumByK
 * @author: chanzhugang
 * @create: 2022/08/19 16:35
 */
public class CombinationSumByK {

    /**
     * 216 组合总和 III
     *
     * @param k
     * @param n
     * @return
     */
    private List<List<Integer>> result = new ArrayList<>();

    public List<List<Integer>> combinationSum(int k, int n) {
        /**
         * 1-9 中 取k个数的和为n， 每个数只能用一次
         * 比如k = 3， n = 7 , [1, 2, 4]
         */
        backtrack(k, n, 1, 0, new ArrayList<Integer>());
        return result;
    }

    private void backtrack(int k, int n, int step, int sum, List<Integer> path) {
        if (sum == n && path.size() == k) {
            result.add(new ArrayList<>(path));
            return;
        }
        if (sum > n || path.size() > k || step > 9) {
            // 剪枝
            return;
        }
        // 不选
        backtrack(k, n, step + 1, sum, path);

        // 选
        path.add(step);
        backtrack(k, n, step + 1, sum + step, path);
        path.remove(path.size() - 1);
    }
}